import os
import logging

from agent.feature.base import Feature
from agent.common.system import sysCommand
from agent.common.config import Config


logger = logging.getLogger('common')


class Zlib(Feature):
    __domain__  = "net"
    __feature__ = "zlib_optimized"
    __lib_name__= "zlib.al8.aarch64.rpm"
    
    def __init__(self) -> None:
        # * check if gzip feature is available in this vm
        super().__init__(self.__domain__, self.__feature__)
        arch = sysCommand("arch")
        if arch != "aarch64":
            raise Exception("gzip feature is unavailable in arch '{}'".format(arch))
        
        if not os.path.exists(os.path.join(Config.LIB_PATH, self.__lib_name__)):
            raise Exception("lib file do not exists: {}".format(
                        os.path.join(Config.LIB_PATH, self.__lib_name__)))

        self.rpm_name = sysCommand("rpm -q {}".format(os.path.join(Config.LIB_PATH, self.__lib_name__)))
        
    def set_value(self, value):
        assert value in ['on', 'off']
        if value == self.get_value():
            return
        
        if value == "on":
            sysCommand("rpm -ivh {} --force".format(self.__lib_name__), 
                       cwd = Config.LIB_PATH, log = True)
        else:
            sysCommand("rpm -e {}".format(self.rpm_name), 
                       cwd = Config.LIB_PATH, log = True)

    def get_value(self):
        # * return current feature value 'on' or 'off'
        try:
            return "on" if sysCommand(
                "rpm -qa | grep {}".format(self.rpm_name
            )) != "" else "off"
        
        except Exception:
            return "off"


    # * By default, the backup() function uses the get_value() function to read the current parameter value
    # * and saves it in a backup file ( in Config.BACKUP_PATH, named as 'net_erdma.json' ). 
    # * The rollback() function reads the backup file and uses the set_value() function to roll back the parameter value. 
    # * If the backup/rollback functions require additional logic, they can be overwritten here.
    
    # def rollback(self):
    #     pass
    
    # def backup(self):
    #     pass

if __name__ == "__main__":
    # * Recommended Unit Test Cases
    handler = Zlib()
    handler.backup()
    handler.set_value("on")
    handler.rollback()